<?php

class Paula
{
	
	public static function arrayToXlink($sons){

		  asort($sons); 
		  $tmp = "";
		  
		  $begin = false;
		  $nbr_begin = false;
		  $last = $begin;
		  $nbr_last = $nbr_begin;
		  $bracket = false;
		  while (list($id,$son_id) = each($sons)) 
		  {
		      if($begin!=false)
		      {
		          $nbr_sons = preg_split("/_/",$son_id);
		          $nbr_sons = $nbr_sons[count($nbr_sons)-1];
		          if($nbr_sons!=$nbr_last+1)
		          {
		              if($bracket==false)
		              {
		                  $tmp = $tmp."(";
		                  $bracket = true;
		              }

		              if($nbr_begin==$nbr_last)
		                  $tmp = $tmp."#".$begin;
		              else
		                   $tmp = $tmp."#xpointer(id('".$begin."')/range-to(id('".$last."')))";

		              $begin = $son_id;
		              $last = $begin;
		              $nbr_begin = preg_split("/_/",$begin);
		              $nbr_begin = $nbr_begin[count($nbr_begin)-1];
		              $nbr_last = $nbr_begin;

		              $tmp = $tmp.",";

		          }
		          else
		          {
		              $last = $son_id;
		              $nbr_last = $nbr_sons;
		          }
		      }
		      else
		      {
		          $begin = $son_id;
		          $last = $begin;
		          $nbr_begin = preg_split("/_/",$begin);
		          $nbr_begin = $nbr_begin[count($nbr_begin)-1];
		          $nbr_last = $nbr_begin;
		      }
		  }

		  if($begin==$last)
		      $tmp = $tmp."#".$begin;
		  else
		      $tmp = $tmp."#xpointer(id('".$begin."')/range-to(id('".$last."')))";

		  if($bracket == true)
		      $tmp = $tmp.")";

		  return $tmp;   
	}
	
	
  public static function XlinkToArray($href)
	{
    $array = array();

    if(!(strpos($href,"(") === false) && strpos($href,"(") == 0)
        $href = substr($href,1,strlen($href)-2);

    if($href=="")
        return;

    $ids = preg_split("/,/",$href);
    for($i= 0; $i< count($ids); $i++)
    {
        if(strpos($ids[$i],"#xpointer") === false)
        {
            $tmp = preg_split("/#/",$ids[$i]);
            array_push($array,$tmp[1]);
        }
        else
        {
            $tmp = preg_split("/'/",$ids[$i]);
            $tmp_begin = preg_split("/_/",$tmp[1]);
            $begin = $tmp_begin[count($tmp_begin)-1];
            unset($tmp_begin[count($tmp_begin)-1]);
            $id = implode("_",$tmp_begin);

            $tmp_end = preg_split("/_/",$tmp[3]);
            $end = $tmp_end[count($tmp_end)-1];

            for($j = (int)$begin; $j <= (int)$end; $j++)
            {
                if($j<10)
                    $j = "0".$j;
                array_push($array,$id."_".$j);
            }
        } 
    }
    return $array;
	}
	
	
	public static function copyDTD($path){
		$dtds = array('paula_feat.dtd', 'paula_header.dtd', 'paula_mark.dtd', 'paula_multiFeat.dtd', 'paula_struct.dtd', 'paula_text.dtd');
		foreach($dtds as $dtd)
		{
			copy('uploads/Paula_dtd/'.$dtd, $path.'/'.$dtd);
		}
	}
	
	
	public static function saveInBd($project_name,$userName)
	{
		
		/*for the test*/
		$annoset = Doctrine::getTable('Annoset')->findOneByName($project_name);
		if($annoset && $annoset->count() != 0)
			$annoset->delete();
			
		unset($annoset);//*/
		/*********************/
		
		/*TODO: le project_path est a mettre en variable globale du projet symfo*/
		$_SESSION["project_path"] = "uploads/projects/".$project_name."/";
		$dir = opendir($_SESSION["project_path"]);
		$fileList = array();
		
    while ($File = readdir($dir))
    {
        if($File != "." && $File != ".." && substr_count($File,".xml")==1 && substr_count($File,".sw")==0)
        {
            $fileList[$File] = new DomDocument;
            $fileList[$File]->load($_SESSION["project_path"]."/".$File);
        }
    }
    closedir($dir);
    
    $annoset = new Annoset();
    $annoset->setName($project_name);
    $annoset->setUserName($userName);
    $annoset->save();
    $id_annoset = $annoset->getId();
    
		foreach($fileList as $file_name=>$file)
		{
			$paula = $file->documentElement;
			$header = $paula->firstChild;
			
			while($header->nodeName == '#text')
				$header = $header->nextSibling;
				
			$paula_id = $header->getAttribute('paula_id');
			$file_type = explode('.', $file_name);
			$file_type = $file_type[count($file_type) - 2];
			
			
			$table_file = new File();
			$table_file->setIdAnnoset($id_annoset);
			$table_file->setName($file_name);
			$table_file->setPaulaId($paula_id);
			
			//	Check wether the file use a multifeatList or not
			$isMultiFeatList = 0;
			
			if($file_type == 'text'){
				/*traitement du texte*/
				$cdata = $file->getElementsBytagName('body')->item(0)->nodeValue;

				$text = new Text();
				$text->setIdAnnoset($id_annoset);
				$text->setPaulaId($paula_id);
				$text->setCdata($cdata);
				$text->save();
						
				$table_file->setType('Text');
				$table_file->save();
			}
			else{		
				/*traitement des differentes listes*/
				$paulaList = $header->nextSibling;
				while($paulaList->nodeName == '#text')
					$paulaList = $paulaList->nextSibling;
			
				/*Remember attributes*/
				$attributes_list = array();
				foreach($paulaList->attributes as $attribute)
				{	
					$attributes_list[$attribute->name] = $attribute->nodeValue;
				}
			
				/*base et List_type*/
				$base = null;
				$list_type = null;
				if(isset($attributes_list['base']))
					$base = $attributes_list['base'];
			
				/*list_type is required*/
				$list_type = $attributes_list['type'];
			
				switch($paulaList->nodeName)
				{
					case 'markList':
					$table_name = 'Mark';
					
					/*parcourrir tous les marks*/
					$marks = $paulaList->getElementsByTagName('mark');
					foreach($marks as $mark)
					{
						$mark_attributes = array();
						foreach($mark->attributes as $attribute)
						{
							$mark_attributes[$attribute->name] = $attribute->nodeValue;
						}
					
						/*entree dans la table mark*/
						$entry = new Mark();
						$entry->setIdAnnoset($id_annoset);
						$entry->setPaulaId($paula_id);
						$entry->setListType($list_type);
						$entry->setBase($base);
						$entry->setAttId($mark_attributes['id']);
						$entry->setHref($mark_attributes['href']);
						if(isset($mark_attributes['type']))
							$entry->setType($mark_attributes['type']);
						$entry->save();
						//*/
					}
				
					break;
				
				
					case 'structList':
					$table_name = 'Struct';
					
					/*parcourrir tous les structs*/
					$structs = $paulaList->getElementsByTagName('struct');
					foreach($structs as $struct)
					{
						$struct_attributes = array();
						foreach($struct->attributes as $attribute)
						{
							$struct_attributes[$attribute->name] = $attribute->nodeValue;
						}
					
						/*entree dans la table struct*/
						$entry = new Struct();
						$entry->setIdAnnoset($id_annoset);
						$entry->setPaulaId($paula_id);
						$entry->setListType($list_type);
						$entry->setBase($base);
						$entry->setAttId($struct_attributes['id']);
						$entry->save();
						//*/
						$id_struct = $entry->getId();
					
						/*parcourrir tous les rels*/
						$rels = $struct->getElementsByTagName('rel');
						foreach($rels as $rel)
						{
							$rel_attributes = array();
							foreach($rel->attributes as $attribute)
							{
								$rel_attributes[$attribute->name] = $attribute->nodeValue;
							}

							/*entree dans la table rel*/
							$entry = new Rel();
							$entry->setIdStruct($id_struct);
							if(isset($rel_attributes['id']))
								$entry->setAttId($rel_attributes['id']);
							$entry->setHref($rel_attributes['href']);
							if(isset($rel_attributes['type']))
								$entry->setType($rel_attributes['type']);
							$entry->save();
							//*/
						}
					}
					break;
				
				
					case 'featList':
					$table_name = 'Feat';
					
					/*parcourrir tous les feats*/
					$feats = $paulaList->getElementsByTagName('feat');
					foreach($feats as $feat)
					{
						$feat_attributes = array();
						foreach($feat->attributes as $attribute)
						{
							$feat_attributes[$attribute->name] = $attribute->nodeValue;
						}

						/*entree dans la table feat*/
						$entry = new Feat();
						$entry->setIdAnnoset($id_annoset);
						$entry->setPaulaId($paula_id);
						$entry->setBase($base);
						$entry->setListType($list_type);
						if(isset($feat_attributes['id']))
							$entry->setAttId($feat_attributes['id']);
						$entry->setHref($feat_attributes['href']);
						if(isset($feat_attributes['name']))
							$entry->setName($feat_attributes['name']);
						$entry->setValue($feat_attributes['value']);
						if(isset($feat_attributes['target']))
							$entry->setTarget($feat_attributes['target']);
						if(isset($feat_attributes['description']))
							$entry->setDescription($feat_attributes['description']);
						if(isset($feat_attributes['example']))
							$entry->setExample($feat_attributes['example']);															
						$entry->save();
						//*/
					}				
				
					break;
				
					case 'multiFeatList':
					$table_name = 'Feat';
					$isMultiFeatList = 1;
					
					/*parcourrir tous les multiFeats*/
					$multiFeats = $paulaList->getElementsByTagName('multiFeat');
					foreach($multiFeats as $multiFeat)
					{
						$multiFeat_attributes = array();
						foreach($multiFeat->attributes as $attribute)
						{
							$multiFeat_attributes[$attribute->name] = $attribute->nodeValue;
						}				
						$href = $multiFeat_attributes['href'];
						$multifeat_id = null;
						if(isset($multiFeat_attributes['id']))
							$multifeat_id = $multiFeat_attributes['id'];
					
						/*parcourrir tous les feats*/
						$feats = $multiFeat->getElementsByTagName('feat');
						foreach($feats as $feat)
						{
							$feat_attributes = array();
							foreach($feat->attributes as $attribute)
							{
								$feat_attributes[$attribute->name] = $attribute->nodeValue;
							}

							/*entree dans la table feat*/
							$entry = new Feat();
							$entry->setIdAnnoset($id_annoset);
							$entry->setPaulaId($paula_id);
							$entry->setBase($base);
							$entry->setListType($list_type);
							$entry->setMultifeatId($multifeat_id);
							if(isset($feat_attributes['id']))
								$entry->setAttId($feat_attributes['id']);
							$entry->setHref($href);
							if(isset($feat_attributes['name']))
								$entry->setName($feat_attributes['name']);
							$entry->setValue($feat_attributes['value']);
							if(isset($feat_attributes['target']))
								$entry->setTarget($feat_attributes['target']);
							if(isset($feat_attributes['description']))
								$entry->setDescription($feat_attributes['description']);
							if(isset($feat_attributes['example']))
								$entry->setExample($feat_attributes['example']);															
							$entry->save();
							//*/
						}	
					}					
				
					break;
				
					default:
					break;		
				}

				/*nouvelle entree dans la table file avec table_name*/
				$table_file->setType($table_name);
				$table_file->setMultiFeat($isMultiFeatList);
				$table_file->save();//*/				
			}	
		}   
	}
	
	
	/*public static function getFeatsLists($annoset)
  {
  	$featsLists = array();
  	$visitedFeats = array();
  	$anno_structs = Doctrine::getTable('Struct')->findByIdAnnosetAndListType($annoset->getId(), 'annoSet');
  	foreach($anno_structs as $anno_struct)
  	{
  		$first = true;
  		foreach($anno_struct->getRels() as $rel)
  		{
  			$href = $rel->getHref();
  			if(count(preg_split('/#/', $href)) == 1)
  			{
  				$file = Doctrine::getTable('File')->findOneByNameAndIdAnnoset($href, $annoset->getId());
  				if($file->getType() == 'Feat')
  				{
  					$anno_feat = Doctrine::getTable('Feat')->findOneByIdAnnosetAndListTypeAndHref($annoset->getId(), 'annoFeat', '#'.$rel->getAttId());
  					if($anno_feat)
  						$type = $anno_feat->getValue();
  					else
  						$type = $rel->getAttId();
  					if($type != 'annoFeat')
  					{
  						$layer_name = $anno_struct->getAttId();
  						if($first === true)
  						{
  							$first = false;
  							$featsLists[$layer_name] = array();
  							$visitedFeats[$layer_name] = array();
  						}
  						$featsLists[$layer_name][$type] = array();
  						$visitedFeats[$layer_name][$type] = array();
  						$feats = Doctrine::getTable('Feat')->findByIdAnnosetAndPaulaId($annoset->getId(), $file->getPaulaId());
  						foreach($feats as $feat)
  						{
  							$feat_name = '';
  							if($feat->getName() != '')
  								$feat_name = $feat->getName();
  							else
  								$feat_name = $feat->getListType();
  							if(!in_array($feat_name, $visitedFeats[$layer_name][$type]))
  							{
									array_push($visitedFeats[$layer_name][$type], $feat_name);
									$featsLists[$layer_name][$type][$feat_name] = array();
								}
								if(!in_array($feat->getValue(), $featsLists[$layer_name][$type][$feat_name]))
									array_push($featsLists[$layer_name][$type][$feat_name], $feat->getValue());
  						}
  					}
  				}
  			}
  		}
  	}
  	return $featsLists;
  }//*/
  
	
	private static function getLayerName($element)
	{
		$file = Doctrine::getTable('File')
			->findOneByIdAnnosetAndPaulaId($element->getIdAnnoset(), $element->getPaulaId());
			
		$file_name = 	$file->getName();
		$rels_annoset = Doctrine::getTable('Rel')->findByHref($file_name);
		foreach($rels_annoset as $rel_annoset)
		{
			if($rel_annoset->getStruct()->getIdAnnoset() == $element->getIdAnnoset())
			{
				return $rel_annoset->getStruct()->getAttId();
			}
		}
	}
	
	private static function getFeatsType($element)
	{
		$href_base = '#'.$element->getAttId();
		$file = Doctrine::getTable('File')
			->findOneByIdAnnosetAndPaulaId($element->getIdAnnoset(), $element->getPaulaId());
		$file_name = $file->getName();
		$href_no_base = $file_name.$href_base;
		$feat_base = Doctrine::getTable('Feat')->findOneByIdAnnosetAndHref($element->getIdAnnoset(), $href_base);
		$feat_no_base = Doctrine::getTable('Feat')->findOneByIdAnnosetAndHref($element->getIdAnnoset(), $href_no_base);
		
		if($feat_base)
			$feat = $feat_base;
		else
			$feat = $feat_no_base;
		
		if(!$feat)
			return null;
			
		$feats_type = $feat->getListType();
		$paula_id = $feat->getPaulaId();
		$file_feat = Doctrine::getTable('File')->findOneByIdAnnosetAndPaulaId($element->getIdAnnoset(), $paula_id);
		$anno_feat_rels = Doctrine::getTable('Rel')->findByHref($file_feat->getName());
		foreach($anno_feat_rels as $anno_feat_rel)
		{
			if($anno_feat_rel->getStruct()->getIdAnnoset() == $element->getIdAnnoset())
			{
				$anno_feat = Doctrine::getTable('Feat')
					->findOneByIdAnnosetAndHrefAndListType($element->getIdAnnoset(), '#'.$anno_feat_rel->getAttId(), 'annoFeat');
				if($anno_feat)
					$feats_type = $anno_feat->getValue();
			}
		}
		return $feats_type;	
	}

	/*TODO: OPTIMISE THIS!!!!*/
	public  static function getDefaultFeat($element, $default_feats)
	{
		//$feats_lists = self::getFeatsLists($element->getAnnoset());
		if(! self::getFeatsType($element))
			return $element->getAttId();
			
		//$feat_names = array_keys($feats_lists[self::getLayerName($element)]->getRaw(self::getFeatsType($element)));
		//$default_feat_name = $feat_names[0];
		$default_feat_name = $default_feats[self::getLayerName($element)][self::getFeatsType($element)];
		if($feat_whith_name = Doctrine::getTable('Feat')
			->findOneByIdAnnosetAndHrefAndName($element->getIdAnnoset(), '#'.$element->getAttId(), $default_feat_name))
				$default_feat = $feat_whith_name->getValue();
		else
		{
			$default_feat = Doctrine::getTable('Feat')
				->findOneByIdAnnosetAndHrefAndListType($element->getIdAnnoset(), '#'.$element->getAttId(), $default_feat_name)
				->getValue();
		}
		return $default_feat;
	}
	
	public static function getLevel($element)
	{
		$sons = $element->getSons();
		if(!$sons)
			return 0;
		$max_son_lvl = 0;
		foreach($sons as $son){
			$son_lvl = self::getLevel($son);
			if($son_lvl > $max_son_lvl)
				$max_son_lvl = $son_lvl;
		}
		return ($max_son_lvl + 1);
	}
	
	public static function getLevelTest($element, $entities = null, $elt_rels = null)
	{
		$rels = null;
		if(isset($elt_rels[$element->getAttId()]))
			$rels = $elt_rels[$element->getAttId()];
		$sons = $element->getSonsTest($entities, $rels);
		if(!$sons)
			return array('element' => $element, 'level'=>0, 'sons'=>null);
		$max_son_lvl = 0;
		foreach($sons as $son){
			$son_elt = self::getLevelTest($son['son'], $entities, $elt_rels);
			$son_lvl = $son_elt['level'];
			if($son_lvl > $max_son_lvl)
				$max_son_lvl = $son_lvl;
		}
		$level = $max_son_lvl + 1;
		$node = array('element' => $element, 'level'=>$level, 'sons'=>$sons);
		return $node;//*/
		//return $level;
		//return $sons;
	}
	
	
	/*public function getDefaultFeat()
	{
		$feats_lists = $this->getAnnoset()->getFeatsLists();
		if(! $this->getFeatstype())
			return $this->getAttId();
			
		$feat_names = array_keys($feats_lists[$this->getLayerName()][$this->getFeatsType()]);
		$default_feat_name = $feat_names[0];
		if($feat_whith_name = Doctrine::getTable('Feat')
			->findOneByIdAnnosetAndHrefAndName($this->getIdAnnoset(), '#'.$this->getAttId(), $default_feat_name))
				$default_feat = $feat_whith_name->getValue();
		else
		{
			$default_feat = Doctrine::getTable('Feat')
				->findOneByIdAnnosetAndHrefAndListType($this->getIdAnnoset(), '#'.$this->getAttId(), $default_feat_name)
				->getValue();
		}
		return $default_feat;
	}//*/	
	
	/**
	 * Export data from PAULA format to the MEDIA/LUNA format file.
	 * 
	 * @param $projectName
	 */
	public static function paulaToMediaLuna($projectName,$filename) {
		$folder = sfConfig::get('sf_upload_dir')."/exported_file/";
		// The DomDocument we will processed
		$imp = new DOMImplementation();
		$document = $imp->createDocument(null, 'corpus');
		$document->encoding = 'UTF-8';
		$document->formatOutput = true;
		
		$dom_corpus = $document->documentElement;
		$projectNameExploded = explode('.',$projectName);
		//	getting words before the '.' characater
		$corpusname = $projectNameExploded[0];
		$dom_corpus->setAttribute('corpusname',$corpusname);
		
		$dom_body = $document->CreateElement('body');
		
		self::buildTurnTags($projectName , $dom_body, $document);
		
		$dom_corpus->appendChild($dom_body);
		
		if(!empty($filename)) {
			// save file
			if(!$document->save($folder.$filename.'.xml')) {
				die("Error:saving media file");
			}
		}
		
		/*// Output headers
	    header('Content-type: "text/xml"; charset="utf8"');
	    header('Content-disposition: attachment; filename="example.xml"');
	
		// Output content
	    echo $document->saveXML();*/
	}
	
	
	/**
	 * Build turn tags From Paula to MEDIA/LUNA
	 * @param $projectName : The project's name
	 * @param $dom_body
	 */
	private static function buildTurnTags($projectName,$dom_body,$domDocument) {
		$folder = sfConfig::get('sf_upload_dir')."/projects/".$projectName."/";
		$file = $projectName.'.turn.xml';
		
		$document = new DomDocument();
		$document->load($folder.$file);
		
		// Get the document's base
		$listDomMarkList = $document->getElementsByTagName('markList');
		foreach($listDomMarkList as $domMarkList) {
			$xmlBase = $domMarkList->getAttribute('xml:base');
		} 
		
		//	Building turn tags
		$listDomMarks = $document->getElementsByTagName('mark');
		foreach($listDomMarks as $domMark) {
			$dom_turn = $domDocument->CreateElement('turn');
			$paula_id = $domMark->getAttribute('id');
			
			$domMarkHref = $domMark->getAttribute('xlink:href');
			
			$paula_id_exploded = explode('turn_',$paula_id);
			
			$turn_media_id = $paula_id_exploded[1];
			
			$dom_turn->setAttribute("id",$turn_media_id);
			
			self::fillTurnTag($dom_turn,$domMarkHref,$domDocument,$xmlBase,$projectName);

			$dom_body->appendChild($dom_turn);
		}
	}
	
	/**
	 * Fill the Turn Tag
	 * 
	 * @param $dom_turn 
	 * @param $href The xlink:href attribute 
	 * @param $domDocument 
	 * @param $xmlBase 
	 * @param $projectName
	 */
	private static function fillTurnTag($dom_turn , $href,$domDocument,$xmlBase,$projectName) {
		$dom_trans = $domDocument->CreateElement("trans");
		//	get the tok ids
		$listTokId = self::XlinkToArray($href);
		if($listTokId != null ) {
			$listDomMark = self::getDomMarksById($listTokId,$xmlBase,$projectName);
		
			$folder = sfConfig::get('sf_upload_dir')."/projects/".$projectName."/";
			$file = $projectName.'.text.xml';
			$document = new DomDocument();
			$document->load($folder.$file);
			
			$listDomBody = $document->getElementsByTagName("body");
			foreach($listDomBody as $domBody) {
				$text = $domBody->nodeValue;
			}
			$theText = "";
			//	Mark text
			$listText = array();
			//	take the text
			foreach($listDomMark as $domMark) {
				$href = $domMark->getAttribute("xlink:href");
		  		$href = explode(',', $href);
		  		$start = $href[2];
		  		$end = substr($href[3], 0, -2);
		  		
		  		$textSolo = mb_substr($text, $start-1, $end, 'UTF-8');
		  		
		  		$numberOfElement = array_push($listText,$textSolo);  		
			}
			foreach($listText as $text){
				$theText = $theText.$text;
			}
			$dom_trans->nodeValue = $theText;
			
			$dom_turn->appendChild($dom_trans);
			
			self::buildTokenTags($dom_turn,$listDomMark,$listText,$domDocument);
			self::buildAttvaluesTags($dom_turn,$domDocument,$projectName);
			self::buildFramesTags($dom_turn,$domDocument,$projectName);
		}
	}
	/**
	 * Generate a Luna Id from a Mark Luna Id
	 * @param unknown_type $id
	 */
	private static function buildLunaIdByPaulaId($id) {
		$mark_id = $id;
		$mark_id_exploded = explode('_',$mark_id);
		$tok_id = "";
		$begin = 0;
		
		foreach($mark_id_exploded as $string) {
			if($begin > 0) {
				if($begin > 1)
					$tok_id = $tok_id."_".(int)$string;
				else
					$tok_id = $tok_id.(int)$string;	
			}
			$begin++;
		}
		return $tok_id;
	}
	
	/**
	 * Build the tokensTag fo the trun tag
	 * 
	 * @param $dom_turn
	 * @param $listDomMark	The DomMarkList
	 * @param $listText Text of the DomMark
	 */
	private static function buildTokenTags($dom_turn,$listDomMark,$listText,$domDocument) {
		$dom_tokens = $domDocument->CreateElement("tokens");
		$nb = count($listDomMark);
		$dom_tokens->setAttribute("nb",$nb);
		$i = 0;
		foreach($listDomMark as $domMark) {
			$tok_id = self::buildLunaIdByPaulaId($domMark->getAttribute('id'));
			
			$text = $listText[$i];
			
			$dom_token = $domDocument->CreateElement('token');
			$dom_token->setAttribute('id',$tok_id);
			$dom_token->setAttribute('type',"wtoken");
			$dom_token->nodeValue = $text;
			
			$dom_tokens->appendChild($dom_token);
			$i++;
		}
		
		$dom_turn->appendChild($dom_tokens);
	}
	
	private static function buildAttvaluesTags($dom_turn,$domDocument,$projectName) {
		$folder = sfConfig::get('sf_upload_dir')."/projects/".$projectName."/";
		$file = $projectName.'.att_feats.xml';
		
		$document = new DomDocument();
		$document->load($folder.$file);
		
		$dom_attvalues = $domDocument->CreateElement("attvalues");
		
		// Get the document's base
		$listDomMultiFeatList = $document->getElementsByTagName('multiFeatList');
		foreach($listDomMultiFeatList as $domMultiFeatList) {
			$xmlBase = $domMultiFeatList->getAttribute('xml:base');
		} 
		
		$listDomMultiFeat = $document->getElementsByTagName('multifeat');
		//	The attvalues tag's nb attribute;
		$nbAttvalues = 0;
		foreach($listDomMultiFeat as $domMultiFeat) {
			
			$pattern = $dom_turn->getAttribute("id");
			$subject = $domMultiFeat->getAttribute("xlink:href");
			
			//	Check wether this multiFeat is for the current turn
			if(strpos($subject,$pattern) !== FALSE) {
				$dom_attvalue = $domDocument->CreateElement("attvalue");
				
				$tmp_id = self::buildLunaIdByPaulaId($subject);
				
				//basis of 50
				$tmp_id = explode($dom_turn->getAttribute("id")."_50",$tmp_id);
				$tmp_id = $dom_turn->getAttribute("id")."_50".(int)$tmp_id[1];
				$att_id = $tmp_id;
				
				$dom_attvalue->setAttribute("id",$att_id);
				
				$listFeat = $domMultiFeat->getElementsByTagName('feat');
				
				foreach($listFeat as $feat) {
					$dom_attvalue->setAttribute($feat->getAttribute("name") , $feat->getAttribute("value"));
				}
				self::fillAttvalueTag($dom_attvalue,$subject,$projectName);
				$dom_attvalues->appendChild($dom_attvalue);	
				$nbAttvalues++;
			}
		}
		$dom_attvalues->setAttribute("nb",$nbAttvalues);
		$dom_turn->appendChild($dom_attvalues);
	}
	
	/**
	 * Fill the attvalue tag
	 * @param unknown_type $dom_attvalue
	 * @param unknown_type $href The multiFeat href
	 */
	private static function fillAttvalueTag($dom_attvalue,$href,$projectName) {
		$folder = sfConfig::get('sf_upload_dir')."/projects/".$projectName."/";
		$file = $projectName.'.att.xml';
		
		$document = new DomDocument();
		$document->load($folder.$file);
		
		// Get the document's base
		$listDomMarkList = $document->getElementsByTagName('markList');
		foreach($listDomMarkList as $domMarkList) {
			$xmlBase = $domMarkList->getAttribute('xml:base');
		}
		
		$file2 = $projectName.'.text.xml';
		$document2 = new DomDocument();
		$document2->load($folder.$file2);
		
		$listDomBody = $document2->getElementsByTagName("body");
		foreach($listDomBody as $domBody) {
			$text = $domBody->nodeValue;
		}
		
		$mark_id = explode("#",$href);
		$mark_id = $mark_id[1];
		
		$listLunaId = array();
		$theText = "";		
		$listDomMark = $document->getElementsByTagName("mark");
		foreach($listDomMark as $domMark) {
			if($domMark->hasAttribute("id")) {
				if($domMark->getAttribute("id") == $mark_id) {
					$array_tok_id = self::XlinkToArray($domMark->getAttribute("xlink:href"));
					
					foreach($array_tok_id as $tok_id) {
						array_push($listLunaId,self::buildLunaIdByPaulaId($tok_id));			
					}
					
					$span = "";
					foreach($listLunaId as $lunaId) {
						if($span != "") {
							$span = "$span $lunaId";
						} else {
							$span = $lunaId;
						}
					}
					$dom_attvalue->setAttribute("span",$span);
					
					$listDomMarkFromTok = self::getDomMarksById($array_tok_id,$xmlBase,$projectName);
					foreach($listDomMarkFromTok as $domMarkFromTok) {
						$href = $domMarkFromTok->getAttribute("xlink:href");
				  		$href = explode(',', $href);
				  		$start = $href[2];
				  		$end = substr($href[3], 0, -2);
				  		
				  		$textSolo = mb_substr($text, $start-1, $end, 'UTF-8');
				  		
				  		
				  		$theText = $theText.$textSolo;  
					}
					
					$dom_attvalue->nodeValue = $theText;
				}
			}
		}
	}
	
	/**
	 * get the Mark dom document object which has an id into the array in the the $file
	 * @param $array_id
	 * @param $file
	 */
	private static function getDomMarksById($array_id,$file,$projectName) {
		$folder = sfConfig::get('sf_upload_dir')."/projects/".$projectName."/";
		$document = new DomDocument();
		$document->load($folder.$file);
		
		$listDomMarks = $document->getElementsByTagName('mark');
		$array_dom_mark = array();
		foreach($listDomMarks as $domMark) {
			if($domMark->hasAttribute("id")) {
				if(in_array($domMark->getAttribute("id") , $array_id )) {
					array_push($array_dom_mark,$domMark);
				}		
			}
		}
		$tmp = self::XlinkToArray("LUNA_DEV_CRICRI.13.att.xml#att_13_3_5001");
		return $array_dom_mark;
	}
	
	private static function buildFramesTags($dom_turn,$domDocument,$projectName) {
		$folder = sfConfig::get('sf_upload_dir')."/projects/".$projectName."/";
		$file = $projectName.'.frame_feats.xml';
		
		$document = new DomDocument();
		$document->load($folder.$file);
		
		$dom_frames = $domDocument->CreateElement("frames");
		
		// Get the document's base
		$listDomMultiFeatList = $document->getElementsByTagName('multiFeatList');
		foreach($listDomMultiFeatList as $domMultiFeatList) {
			$xmlBase = $domMultiFeatList->getAttribute('xml:base');
		} 
		
		$listDomMultiFeat = $document->getElementsByTagName('multifeat');
		
		$pattern = $dom_turn->getAttribute("id");
		$arrayDomMultiFeat = array();
		foreach($listDomMultiFeat as $domMultiFeat) {
			$subject = $domMultiFeat->getAttribute("xlink:href");
			//	Check wether this multiFeat is for the current turn
			if(strpos($subject,$pattern) !== FALSE) {
				array_push($arrayDomMultiFeat,$domMultiFeat);
			}
		}
		
		foreach($arrayDomMultiFeat as $domMultiFeat) {
			$dom_frame = $domDocument->CreateElement("frame");
			self::fillFrameTag($dom_frame,$domDocument,$xmlBase,$domMultiFeat,$projectName);
			$dom_frames->appendChild($dom_frame);
		}
						
		$dom_frames->setAttribute("nb",count($arrayDomMultiFeat));
		$dom_turn->appendChild($dom_frames);
	}
	/**
	 * Fill a frame tag
	 * @param unknown_type $dom_frame
	 * @param unknown_type $domDocument
	 * @param unknown_type $xmlBase : The file which ils the base of the tag
	 * @param unknown_type $domMultiFeat
	 */
	private static function fillFrameTag($dom_frame,$domDocument,$xmlBase,$domMultiFeat,$projectName) {
		$paulaId = $domMultiFeat->getAttribute("xlink:href");
		$paulaId = explode("#",$paulaId);
		$paulaId = $paulaId[1];
		
		$lunaId = self::generateFrameTypeIdByPaulaId($paulaId);
		
		$listDomFeat = $domMultiFeat->getElementsByTagName("feat");
		$dom_frame->setAttribute("id",$lunaId);
		foreach($listDomFeat as $domFeat) {
			$dom_frame->setAttribute($domFeat->getAttribute("name") , $domFeat->getAttribute("value"));
		}
		
		$folder = sfConfig::get('sf_upload_dir')."/projects/".$projectName."/";
		$file = $projectName.'.frame.xml';
		
		$document = new DomDocument();
		$document->load($folder.$file);
		$listDomStruct = $document->getElementsByTagName("struct");
		
		foreach($listDomStruct as $domStruct) {
			if($domStruct->getAttribute("id") == $paulaId) {
				$listDomRel = $domStruct->getElementsByTagName("rel");
				// The nb attribute of fes tag
				$fes_nb = 0;
				$dom_fes = $domDocument->CreateElement("fes");
				foreach($listDomRel as $domRel) {
					$linkValue = self::getFrameLinkValue($domRel,$projectName);
					$domRel_paulaId = self::XlinkToArray($domRel->getAttribute("xlink:href"));
					//	get the attribute;
					foreach($domRel_paulaId as $id);
					$domRel_paulaId = $id;
					
					$explodedPaulaId = explode('_',$domRel_paulaId);
					
					if($explodedPaulaId[0] == "att") {
						$lunaId = self::buildLunaIdByPaulaId($domRel_paulaId);
						//	basis of 50
						$lunaId = self::setBasisFiftyId($lunaId);
						$type = "attvalue";
					} else {
						$lunaId = self::generateFrameTypeIdByPaulaId($domRel_paulaId);
						$type= "frame";
					}
					
					
					if($linkValue == "target") {
						$dom_target = $domDocument->CreateElement("target");
							$dom_fenode = $domDocument->CreateElement("fenode");
							$dom_fenode->setAttribute("idref",$lunaId);
							$dom_fenode->setAttribute("type",$type);
						$dom_target->appendChild($dom_fenode);
						$dom_frame->appendChild($dom_target);
					} else {
						$domRelId = self::generateFrameTypeIdByPaulaId($domRel->getAttribute("id"));
					
						$dom_fe = $domDocument->CreateElement("fe");
						$dom_fe->setAttribute("id",$domRelId);
							$dom_fenode = $domDocument->CreateElement("fenode");
							$dom_fenode->setAttribute("idref",$lunaId);
							$dom_fenode->setAttribute("type",$type);
						$dom_fe->appendChild($dom_fenode);
						$dom_fe->setAttribute("name",$linkValue);
						$dom_fes->appendChild($dom_fe);
						$fes_nb++;
					}
				}
				$dom_fes->setAttribute("nb",$fes_nb);
				$dom_frame->appendChild($dom_fes);
			}		
		}
	}
	/**
	 * Set The Id in basis 50
	 * e.g: 13_2_5001 become 13_2_501
	 * 		13_2_5000 become 13_2_500
	 * 		13_2_5012 become 13_2_5012
	 * @param unknown_type $id
	 */	
	private static function setBasisFiftyId($id) {
		$explodedId = explode("_50",$id);
		if(count($explodedId) > 1) {
			$lunaId = $explodedId[0]."_50".(int)$explodedId[1];
		} else {
			$explodedId = explode("_",$id);
			$lunaId = "";
			foreach($explodedId as $tmpId) {
				if($lunaId != "") {
					$lunaId .= "_$tmpId";
				} else {
					$lunaId = $tmpId;
				}
			}
		}
		
		return $lunaId;
	}
	
	private static function generateFrameTypeIdByPaulaId($paulaId) {
		$id = preg_split("/[a-zA-Z]+_/",$paulaId);
		$id = $id[1];
		
		$array = explode("_",$id);
		$finalId = "";
		foreach($array as $thing) {
			if(!is_numeric($thing)) {
				$array_split = str_split($thing);
				$numeric="";
				$notNumeric="";
				foreach($array_split as $tmp) {
					if(!is_numeric($tmp)) {
						$notNumeric=$notNumeric.$tmp;
						
					} else {
						$numeric=$numeric.$tmp;
					}
				}
				$thing=$notNumeric.(int)$numeric;
			}
			if(!empty($finalId))	
				$finalId = $finalId."_".$thing;
			else
				$finalId = $thing;
		}
		
		return $finalId;	
	}
	
	/**
	 * Get The link value of the rel tag
	 * @param $domRel
	 */
	private static function getFrameLinkValue($domRel,$projectName) {
		$folder = sfConfig::get('sf_upload_dir')."/projects/".$projectName."/";
		$file = $projectName.'.frame_links_feats.xml';
		
		$document = new DomDocument();
		$document->load($folder.$file);
		
		$listDomFeat = $document->getElementsByTagName("feat");
		foreach($listDomFeat as $domFeat) {
			$featId = $domFeat->getAttribute("xlink:href");
			$featId = explode("#",$featId);
			$featId = $featId[1];
			
			if($featId == $domRel->getAttribute("id")) {
				return $domFeat->getAttribute("value");
			}
		}
		return "";
	}
	
	/**
	 * Export data From database to PAULA
	 * 
	 * @param $id_annoset : The annoset's id
	 * @return The The projectName
	 */
	public static function databaseToPaula($id_annoset) {
		//	list of files
		$file_list = Doctrine::getTable('File')
			->CreateQuery('f')->select()->where('f.id_annoset=?',$id_annoset)
			->execute();
		
		$annoset_list = Doctrine::getTable('Annoset')
			->CreateQuery('a')->select()->where('a.id=?',$id_annoset)
			->execute();
		
		foreach($annoset_list as $annoset);
		
		foreach($file_list as $file) {
			
			if(strcmp($file->getType(),"Feat") == 0 ) {
				// build all struct tags
				self::buildFeatTags($file,$annoset);
			} else {
			
				// The DomDocument we will processed
				$imp = new DOMImplementation();
				$dtd = $imp->createDocumentType('paula', null, 'paula_'.strtolower($file->getType()).'.dtd');
				$document = $imp->createDocument(null, 'paula', $dtd);
				$document->encoding = 'UTF-8';
				$document->formatOutput = true;
				
				$paula = $document->documentElement;
				$paula->setAttribute('version', '1.0');
				
				$header = $document->createElement('header');
				$header->setAttribute('paula_id', $file->getPaulaId());
				$paula->appendChild($header);
					
				if(strcmp($file->getType(),"Mark") == 0 ) {
					// build all mark tags
					self::buildMarkTags($document,$paula,$file,$id_annoset);
				}
				
				if(strcmp($file->getType(),"Text") == 0 ) {
					// build all text tags
					self::buildTextTags($document,$paula,$file,$id_annoset);
				}
				
				if(strcmp($file->getType(),"Struct") == 0 ) {
					// build all struct tags
					self::buildStructTags($document,$paula,$file,$id_annoset);
				}
				
				// save file
				if(!$document->save(sfConfig::get('sf_upload_dir')."/projects/".$annoset->getName()."/".$file->getName())) {
					die("Error:saving file");
				}
			} // if
			
		}
		
		return $annoset->getName();
	}
	
	/**
	 * Build Paula file for "Mark" type
	 * 
	 * @param $document		The DomDocument
	 * @param $paula		DomObject with tag "paula" which will contain marklist
	 * @param $file			The mark Object
	 * @param $id_annoset	The annoset's id
	 */
	private static function buildMarkTags($document,$paula , $file, $id_annoset) {
		$markList = Doctrine::getTable('Mark')
			->CreateQuery('m')->select()
			->where('paula_id=?',$file->getPaulaId())->addWhere('id_annoset=?',$id_annoset)
			->execute();
		foreach($markList as $mark) {
			$base = $mark->getBase();
			$type = $mark->getListType();
			break;
		}
		$dom_markList = $document->createElement('markList');
		$dom_markList->setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink");
		$dom_markList->setAttribute("xml:base",$base); 
		$dom_markList->setAttribute("type",$type); 
		
		foreach($markList as $mark) {
			$dom_mark = $document->createElement('mark');
			$dom_mark->setAttribute("id",$mark->getAttId());
			$dom_mark->setAttribute("xlink:href",$mark->getHref());
			$dom_markList->appendChild($dom_mark);
		}
		$paula->appendChild($dom_markList);
	}
	
	/**
	 * Build paula file for "Struct" type
	 * 
	 * @param $document		The DomDocument
	 * @param $paula		DomObject with tag "paula" which will contain strcutlist
	 * @param $file			The mark Object
	 * @param $id_annoset	The annoset's id
	 */
	private static function buildStructTags($document,$paula , $file, $id_annoset) {
		$structList = Doctrine::getTable('Struct')
			->CreateQuery('s')->select()
			->where('paula_id=?',$file->getPaulaId())->addWhere('id_annoset=?',$id_annoset)
			->execute();
		$type;
		foreach($structList as $struct) {
			$type = $struct->getListType();
			break;
		}
		
		$dom_structList = $document->createElement('structList');
		$dom_structList->setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink");
		if(isset($type))
			$dom_structList->setAttribute("type",$type); 
		 
		
		foreach($structList as $struct) {
			$dom_struct = $document->createElement('struct');
			$dom_struct->setAttribute("id",$struct->getAttId());
			//	create all dom_struct's rel tags
			self::buildRelStructTags($document,$dom_struct,$struct->getId());
			$dom_structList->appendChild($dom_struct);
		}
		
		$paula->appendChild($dom_structList);
		
	}
	
	/**
	 * 
	 * @param $document		The DomDocument
	 * @param $dom_struct	DomObject with tag "struct" which will contain rel
	 * @param $id_struct	The struct's id
	 */
	private static function buildRelStructTags($document,$dom_struct,$id_struct) {
		$relList = Doctrine::getTable('Rel')
			->CreateQuery('r')->select()
			->where('id_struct=?',$id_struct)->execute();
		foreach($relList as $rel) {
			$dom_rel = $document->createElement('rel');
			$dom_rel->setAttribute("id",$rel->getAttId());
			$dom_rel->setAttribute("xlink:href",$rel->getHref());
			$dom_struct->appendChild($dom_rel);
		}
	}
	
	/**
	 * Build paula file for "Text" type
	 * 
	 * @param $document		The DomDocument
	 * @param $paula		DomObject with tag "paula" which will contain text
	 * @param $file			The mark Object
	 * @param $id_annoset	The annoset's id
	 */
	private static function buildTextTags($document,$paula , $file, $id_annoset) {
		$textList = Doctrine::getTable('Text')
			->CreateQuery('t')->select()
			->where('paula_id=?',$file->getPaulaId())->addWhere('id_annoset=?',$id_annoset)
			->execute();
		
		foreach($textList as $text);
			
		$dom_body = $document->CreateElement('body');
		$dom_body->nodeValue = $text->getCdata();
		$paula->appendChild($dom_body);
	}
	
	/**
	 * Build paula file for "Feat" type
	 * 
	 * @param $file			The mark Object
	 * @param $annoset		The annoset
	 */
	private static function buildFeatTags($file, $annoset) {
		
		
		// The DomDocument we will processed
		$imp = new DOMImplementation();
		switch($file->getMultiFeat()) {
			case '1':
				$dtd = $imp->createDocumentType('paula', null, 'paula_multiFeat.dtd');
				break;
			case '0':
				$dtd = $imp->createDocumentType('paula', null, 'paula_'.strtolower($file->getType()).'.dtd');
				break;
		} // switch

		$document = $imp->createDocument(null, 'paula', $dtd);
		$document->encoding = 'UTF-8';
		$document->formatOutput = true;
		
		$paula = $document->documentElement;
		$paula->setAttribute('version', '1.0');
		
		$header = $document->createElement('header');
		$header->setAttribute('paula_id', $file->getPaulaId());
		$paula->appendChild($header);
		
		$featList = Doctrine::getTable('Feat')
			->CreateQuery('f')->select()
			->where('paula_id=?',$file->getPaulaId())->addWhere('id_annoset=?',$annoset->getId())
			->orderBy('href ASC')
			->execute();
			
		switch($file->getMultiFeat()) {
			case '1':
				$node = self::buildMultiFeatListTags($document,$featList);
				break;
			case '0':
				$node = self::buildFeatListTags($document,$featList);
				break;
		} // switch
		$paula->appendChild($node);
		// save file
		if(!$document->save(sfConfig::get('sf_upload_dir')."/projects/".$annoset->getName()."/".$file->getName())) {
			die("Error:saving file");
		}
	}
	
	/**
	 * Build multifeatList tags accroding to $featList object.
	 * 
	 * @param $document		The DomDocument
	 * @param $featList		Doctrine_Table Object
	 */
	private static function buildMultiFeatListTags($document,$featList) {
		$dom_multifeatList = $document->CreateElement('multiFeatList');
		$dom_multifeatList->setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink");
		// get base and type
		foreach($featList as $feat) {
			$base = $feat->getBase();
			$type = $feat->getListType();
			break;
		}
		
		$dom_multifeatList->setAttribute("xml:base",$base);
		$dom_multifeatList->setAttribute("type",$type);
		
		//the current feat's href
		$current_href = NULL;
		$dom_multifeat = NULL;
		foreach($featList as $feat) {
			if(strcmp($feat->getHref(),$current_href) != 0) {
				if($current_href != NULL ) {
					$dom_multifeatList->appendChild($dom_multifeat);
				}
				$current_href = $feat->getHref();
				$dom_multifeat = $document->CreateElement('multifeat');
				$dom_multifeat->setAttribute("xlink:href",$feat->getHref());
			}
			
			$dom_feat = $document->CreateElement('feat');
			$dom_feat->setAttribute('name',$feat->getName());
			$dom_feat->setAttribute('value',$feat->getValue());
			$dom_multifeat->appendChild($dom_feat);
		}
		//last item
		if($current_href != NULL ) {
			$dom_multifeatList->appendChild($dom_multifeat);
		}
		return $dom_multifeatList;
	}
	
/**
	 * Build featList tags accroding to $featList object.
	 * 
	 * @param $document		The DomDocument
	 * @param $featList		Doctrine_Table Object
	 * @return The DomDocument with tag featList
	 */
	private static function buildFeatListTags($document,$featList) {
		$dom_featList=$document->CreateElement('featList');
		$dom_featList->setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink");
		
		// get base and type
		foreach($featList as $feat) {
			$base = $feat->getBase();
			$type = $feat->getListType();
			break;
		}
		if(isset($base) && !empty($base)) {
			$dom_featList->setAttribute("xml:base",$base);
		}
		if(isset($type) && !empty($type)) 
			$dom_featList->setAttribute("type",$type);
		
		foreach($featList as $feat) {
			$dom_feat=$document->CreateElement('feat');
			$dom_feat->setAttribute("xlink:href",$feat->getHref());
			$dom_feat->setAttribute("value",$feat->getValue());
			$dom_featList->appendChild($dom_feat);
		}
		
		return $dom_featList;
	}

} 
?>






















